<?php
require_once('tar.php');

function scandir_r($dir,$r=false) {
    $r = ($r?$r:strlen($dir));
    $return = array();
    $d = scandir($dir);
    foreach ($d as $file) {
        if ( ($file!='.') && ($file!='..') && (!strpos($file,'~')) ) {
            if (is_file($dir . $file)) {
                $return[] = substr($dir,$r) . $file;
            } elseif (is_dir($dir . $file)) {
                $return[] = substr($dir,$r) . $file.'/';
                $return = array_merge($return,scandir_r($dir . $file . '/',$r));
            }
        }
    }
    arsort($return);
    return $return;
}


function dir_bundle($dir,$projectdir,$maxsize) {
    $files = array();
    $dirs = array();
    foreach ($dir as $file) {
        if (is_dir($projectdir.$file)) {
            $dirs[] = $file;
        } else $files[$file] = filesize($projectdir.$file);
    }
    arsort($files);
    
    
    $tars = array(
        array('size'=>0,'files'=>array()),
    );
    $i=0;
    foreach ($dirs as $dir) {
        if (($tars[$i]['size']+512) > $maxsize) {
            $i++;
            $tars[$i] = array('size'=>0,'files'=>array());
        }
        $tars[$i]['files'][] = $dir;
        $tars[$i]['size'] += 512;
    }
    
    
    foreach ($files as $file => $size) {
        // Get emptiest tar
        $i = 0;
        foreach ($tars as $k => $tar) {
            if ($tar['size'] < $tars[$i]['size']) $i = $k;
        }
        
        if (($tars[$i]['size']+512+$size) > $maxsize) {
            $i = count($tars);
            $tars[$i] = array('size'=>0,'files'=>array());
        }
        $tars[$i]['files'][] = $file;
        $tars[$i]['size'] += (512+$size);
    }
    
    return $tars;
}



function make_tar($tar,$file,$repodir,$projectdir) {$file .= '.tar';
    $tarfile = new tar();
    $tarfile->create($repodir.$file);
    foreach ($tar['files'] as $f) {
        $tarfile->add($f,$projectdir.$f);
    }
    $tarfile->save();
    
    $fh = fopen($repodir.$file,'rb');
    $gh = gzopen($repodir.$file.'.gz','wb');
    while ($block = fread($fh,512)) gzwrite($gh,$block);
    fclose($fh);
    gzclose($gh);
    
    chmod($repodir.$file,0666);
    chmod($repodir.$file.'.gz',0666);
    
    return array('file'=>$file,'md5'=>md5_file($repodir.$file));
}


function make_lst($tars,$name,$repodir) {
    $data = '{
    version:\'1\',
    mincompatable:1,
    files:[';
    foreach ($tars as $tar) {
        $data .= "\n" . '        {name:\'' . $tar['file'] . '\', hash:\'' . $tar['md5'] . '\'},';
    }
    
    $data = substr($data,0,strlen($data)-1);
    $data .= "\n" . '    ]
}';
    if ($fh = fopen($repodir.$name.'.lst','w')) {
        fwrite($fh,$data);
        fclose($fh);
        chmod($repodir.$name.'.lst',0666);
    }
    return $data;
}

?>